<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Http\Requests\RegisterPost;
use App\Http\Requests\LoginPost;
use App\Http\Requests\Email;
use App\Models\User;
use App\Logic\UserLogic;
use App\Logic\MailLogic;
use App\Jobs\ProcessMail;

class LoginController extends Controller
{

    protected $userMdl;

    public function __construct(User $user)
    {
        $this->userMdl = $user;
    }

    /**
     * 注册
     * User: 920078259@qq.com
     * @param RegisterPost $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(RegisterPost $request, MailLogic $mailLogic)
    {

        if ($request->hasAny(['email', 'name', 'password'])) {
            // 验证数据
            $request->validated();

            // 验证邮件注册码
            $result = $mailLogic->checkRegister($request->post('email'), $request->post('code', 1));
            if (!$result) {
                return $this->json([], '验证码错误', 400);
            }

            // 录入数据
            $this->userMdl->addData($request->only(['email', 'name', 'password']));

            return $this->json();
        }

        return $this->json([], '请求错误', 400);
    }

    /**
     * 登录
     * User: 920078259@qq.com
     * @param LoginPost $request
     * @param UserLogic $userLogic
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(LoginPost $request, UserLogic $userLogic)
    {

        if ($request->hasAny(['email', 'password'])) {
            // 验证数据
            $request->validated();
            // 验证账号密码
            $postData = $request->only(['email', 'password']);
            $res = $userLogic->checkPassword($postData['email'], $postData['password']);
            if ($res['code'] == 0) {
                return $this->json([], $res['msg'], 400);
            }

            return $this->json($res['data']);
        }

        return $this->json([], '请求错误', 400);
    }

    /**
     * 发送邮件
     * @param Email $request
     * @param MailLogic $mailLogic
     * @return \Illuminate\Http\JsonResponse
     */
    public function sendRegisterMail(Email $request, MailLogic $mailLogic)
    {
        if ($request->hasAny(['email'])) {
            // 验证数据
            $request->validated();

            // 发送邮件
            $postData = $request->only(['email']);
            $res = $mailLogic->register($postData['email']);
            if (!$res) {
                return $this->json([], $res, 400);
            }

            // ProcessMail::dispatch($request->post('email'));


            return $this->json();
        }

        return $this->json([], '请求错误', 400);
    }


}
